package leetcodev1.数组;

public class LeetCode48 {

    //原地旋转
    //[0][0]->[0][n]
    //[0][1]->[1][n]
    //[0][2]->[2][n]
    //向左旋转90度=上下翻转+对角线翻转
    public void rotate(int[][] matrix) {
        int n = matrix.length;
        // 水平翻转
        for (int i = 0; i < n / 2; ++i) {
            for (int j = 0; j < n; ++j) {
                //上下翻转
                int temp = matrix[i][j];
                matrix[i][j] = matrix[n - i - 1][j];
                matrix[n - i - 1][j] = temp;
            }
        }
        // 主对角线翻转
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < i; ++j) {
                //对角线翻转
                int temp = matrix[i][j];
                matrix[i][j] = matrix[j][i];
                matrix[j][i] = temp;
            }
        }
    }

    //matrix[row][col]->matrix[col][n−row−1]
    //记录tmp然后一次把4个元素进行换位
    //主要在于公式的推导
    public void rotate1(int[][] matrix) {
        int n = matrix.length;
        //只需旋转左上角的方块元素
        for (int i = 0; i < n / 2; ++i) {
            for (int j = 0; j < (n + 1) / 2; ++j) {
                int temp = matrix[i][j];//临时值
                matrix[i][j] = matrix[n - j - 1][i];//第4个象限到第1个
                matrix[n - j - 1][i] = matrix[n - i - 1][n - j - 1];//第3象限到第4象限
                matrix[n - i - 1][n - j - 1] = matrix[j][n - i - 1];//第2象限到第3象限
                matrix[j][n - i - 1] = temp;//第2象限填充tmp
            }
        }
    }

    //开辟新的空间 使用后复制回去
    public void rotate2(int[][] matrix) {
        int n = matrix.length;
        int[][] matrix_new = new int[n][n];
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < n; ++j) {
                matrix_new[j][n - i - 1] = matrix[i][j];
            }
        }
        for (int i = 0; i < n; ++i) {
            for (int j = 0; j < n; ++j) {
                matrix[i][j] = matrix_new[i][j];
            }
        }
    }

}
